#include "HttpCommunicator.h"

#include <sys/ioctl.h>
#include <poll.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <ctype.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <strings.h>
#include <string.h>
#include <errno.h>

#include "StringUtility.h"


//发送http报文请求
ssize_t HttpCommunicator::sendHeader(const Utility::StringMap& properties) {
    std::string buffer(STRING_BUFFER_SIZE, 0);
    int realLength = snprintf(&buffer[0], buffer.size() + 1, "GET %s HTTP/1.1\r\n"\
            "Host: %s\r\n"\
            "Connection: Keep-Alive\r\n"\
            "Content-Type: application/octet-stream\r\n", muriInfo.url.data(), muriInfo.ip.data());

    buffer.resize(realLength);
    for (Utility::StringMap::const_iterator iterator = properties.begin(); iterator != properties.end(); ++iterator){
        buffer.append(iterator->first).append(PROPERTY_SPLITTER).append(iterator->second).append(PROPERTY_END);
    }
    buffer.append(PROPERTY_END);

    return msocket.send(buffer);
}

//解析http报文头
ssize_t HttpCommunicator::parseHeader(HttpHeader& header) {
    NetworkString buffer(1, 0);
    char temp[STRING_BUFFER_SIZE],*ptr;
    memset(temp, 0, sizeof(temp));
    ssize_t len,n = -1;
    while((len = msocket.recv(buffer,0)) != 0) {
        if (buffer[0] == '\n') {

            if (0 == n && *temp == '\r'){
                break;
            }
            temp[n] = 0;
            puts(temp);
            ptr = strstr(temp,"HTTP/1.1");
            if (ptr != NULL) {
                ptr = strchr(ptr,' ');
                ++ptr;
                header.statusCode = atoi(ptr);
            }
            ptr = strstr(temp,"Content-Length:");
            if (ptr != NULL) {
                ptr = strchr(ptr,':');
                ++ptr;
                header.contentLength = std::strtoul(ptr, nullptr, 10);
            }
            ptr = strstr(temp,"Content-Type:");
            if (ptr != NULL) {
                ptr = strchr(ptr,':');
                ++ptr;
                header.contentType = ptr;
            }

            ptr = strstr(temp, CONTENT_RANGE.data());
            if (nullptr != ptr){
                ptr += CONTENT_RANGE.size() + 2;
                header.properties.insert_or_assign(CONTENT_RANGE, ptr);
            }

            ptr = strstr(temp, ETAG.data());
            if (nullptr != ptr){
                ptr += ETAG.size() + 2;
                header.properties.insert_or_assign(ETAG, ptr);
            }

     //       memset(temp, 0, sizeof(temp));
            n = -1;
        } else {
            temp[++n] = buffer[0];
        }
    }

    return 0;
}



